package com.qfedu.aunt.commons.slot.impl;

import com.alibaba.druid.util.StringUtils;
import com.qfedu.aunt.commons.exception.BusinessException;
import com.qfedu.aunt.commons.result.ResponseCode;
import com.qfedu.aunt.commons.slot.base.BaseSlot;
import com.qfedu.aunt.commons.slot.base.SlotChain;
import com.sun.javafx.collections.MappingChange;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author xiaobobo
 * @title: SlotChainManagerImpl
 * @projectName aunt_commons_2209
 * @description: 这个类的作用是调用Slot的实现类来完成校验的
 * @date 2022/11/4  15:29
 */
@Component
public class SlotChainManagerImpl implements SlotChain {
    // String表示的是 slot的实现在在IOC容器中的名字
    // BaseSlot 表示的是要注入的这个对象在IOC中爹
    @Autowired
    private Map<String, BaseSlot> slotMap;

    @Value("${slot.order}")
    private String slotOrder;  //这个是slot的顺序

    @Override
    public void dealReq(HttpServletRequest req) {

       if(StringUtils.isEmpty(slotOrder)){
           throw new BusinessException(
                   ResponseCode.SLOT_ORDER_EXCEPTION.getCode(),
                   ResponseCode.SLOT_ORDER_EXCEPTION.getMessage());
       }
       //程序执行到这里 说明有值
        if(null==slotMap||slotMap.size()==0){
            //说明这个slot是没有实现类的
            throw new BusinessException(
                    ResponseCode.SLOT_IMPL_EXCEPTION.getCode(),
                    ResponseCode.SLOT_IMPL_EXCEPTION.getMessage());
        }
        //程序执行到这里 说明都有值
        if(!slotOrder.contains(",")){
            //表示的是没有，只有一个名字
            BaseSlot baseSlot = slotMap.get(slotOrder);
            if(null==baseSlot){
                //说明名字没有对应上
                throw new BusinessException(
                        ResponseCode.SLOT_NAME_EXCEPTION.getCode(),
                        ResponseCode.SLOT_NAME_EXCEPTION.getMessage());
            }
            //如果执行到这里 说明是正常的
            baseSlot.dealReq(req);
            return ;
        }
        //程序执行到这里 说明有,有多个名字
        String[] splitNames = slotOrder.split(",");
        for (String slotName:splitNames) {
            //接下来找对应的slot实例
            BaseSlot baseSlot = slotMap.get(slotName);
            if(null==baseSlot){
                //说明名字没有对应上
                throw new BusinessException(
                        ResponseCode.SLOT_NAME_EXCEPTION.getCode(),
                        ResponseCode.SLOT_NAME_EXCEPTION.getMessage());
            }
            //执行到这里说明找到了
            baseSlot.dealReq(req);
        }
    }
}
